package com.zhilian.hzrf_oa.mvp.main.view;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.colin.base.BaseActivity;
import com.colin.bean.AppInfo;
import com.colin.constant.Constants;
import com.colin.download.service.DownloadService;
import com.colin.utils.ApplicationManager;
import com.david.gradientuilibrary.GradientIconView;
import com.david.gradientuilibrary.GradientTextView;
import com.zhilian.hzrf_oa.R;
import com.zhilian.hzrf_oa.bean.UpdateBean;
import com.zhilian.hzrf_oa.mvp.main.presenter.MainPresenter;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by colin on 2018/2/26 9:46 .
 */

public class MainActivity extends BaseActivity implements IMainView {

	@BindViews({R.id.gi_chats,R.id.gi_office,R.id.gi_contacts,R.id.gi_about})
	List<GradientIconView> mTabIcons;
	@BindViews({R.id.gt_chats,R.id.gt_office,R.id.gt_contacts,R.id.gt_about})
	List<GradientTextView> mTabText;
	@BindView(R.id.vp_container)
	ViewPager mVpContainer;

	private MainPresenter mPresenter;
	private ProgressBar progressBar;
	private long downloadId;
	private DownloadService.DownloadBinder mDownloadBinder;
	private Disposable mDisposable;//可以取消观察者
	private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mDownloadBinder = (DownloadService.DownloadBinder) service;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mDownloadBinder = null;
		}
	};

	//开始监听进度
	private void startCheckProgress(long downloadId) {
		Observable
			.interval(100, 200, TimeUnit.MILLISECONDS, Schedulers.io())//无限轮询,准备查询进度,在io线程执行
			.filter(times -> mDownloadBinder != null)
			.map(i -> mDownloadBinder.getProgress(downloadId))//获得下载进度
			.takeUntil(progress -> progress >= 100)//返回true就停止了,当进度>=100就是下载完成了
			.distinct()//去重复
			.subscribeOn(Schedulers.io())
			.observeOn(AndroidSchedulers.mainThread())
			.subscribe(new ProgressObserver());
	}


	//观察者
	private class ProgressObserver implements Observer<Integer> {

		@Override
		public void onSubscribe(Disposable d) {
			mDisposable = d;
		}

		@Override
		public void onNext(Integer progress) {
			progressBar.setProgress(progress);//设置进度
		}

		@Override
		public void onError(Throwable throwable) {
			throwable.printStackTrace();
			Toast.makeText(MainActivity.this, "出错", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onComplete() {
			progressBar.setProgress(100);
			Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
		}
	}


	@Override
	protected int layoutRes() {
		return R.layout.activity_main;
	}

	@Override
	protected void initViewData() {
		if (!EasyPermissions.hasPermissions(this, Constants.PERMISSIONS)) {
			EasyPermissions.requestPermissions(this, "需要访问手机存储权限！", 10086, Constants.PERMISSIONS);
		}

		Intent intent = new Intent(MainActivity.this, DownloadService.class);
		startService(intent);
		bindService(intent, mConnection, BIND_AUTO_CREATE);//绑定服务
		mPresenter = new MainPresenter(this);
		mPresenter.checkVersion(this);
	}

	@Override
	protected void initView() {

	}

	@Override
	protected void updateView() {

	}

	@Override
	public void updateApplication(UpdateBean model) {

		final String version_desc = model.getVersion_desc();// 更新说明
		AppInfo info = ApplicationManager.getApplicationVersion(this);
		String app_version = model.getApp_version();// 版本号
		int force_update = model.getForce_update();// 强制更新
		// 判断服务版本号是否大于当前版本号
		String[] arr = app_version.split("\\.");
		int version_code = Integer.parseInt(arr[arr.length - 1]);
		if (version_code > info.getVersionCode()) {
			if (force_update == 1) {
				downloadId = mDownloadBinder.startDownload(Constants.apkUrl);
				startCheckProgress(downloadId);
			} else {
				View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_checkversion, null);
				TextView currentVersion = (TextView) view.findViewById(R.id.tv_current_version);
				TextView updateVersion = (TextView) view.findViewById(R.id.tv_update_version);
				TextView updateDescription = (TextView) view.findViewById(R.id.tv_update_description);
				progressBar = (ProgressBar) view.findViewById(R.id.progress);
				currentVersion.setText("当前版本：v" + info.getVersionCode());
				updateVersion.setText("升级版本：v" + model.getVersion_code());
				updateDescription.setText(version_desc);
				AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
					.setView(view)
					.setTitle("软件升级")
					.setPositiveButton("立即更新", null)
					.setNegativeButton("下次再说", null);
				AlertDialog dialog = builder.create();
				dialog.setCancelable(false);
				dialog.show();
				dialog.getButton(DialogInterface.BUTTON_POSITIVE)
					.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View view) {
							dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setVisibility(View.INVISIBLE);
							downloadId = mDownloadBinder.startDownload(Constants.apkUrl);
							startCheckProgress(downloadId);
						}
					});
			}
		}
	}

	@Override
	protected void onDestroy() {
		if (mDisposable != null) {
			//取消监听
			mDisposable.dispose();
		}
		super.onDestroy();
	}
}
